﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using DevComponents.AdvTree;
using System.Data.SqlClient;
using Tunnel_Cross_Section.menue_frm;
using Tunnel_Cross_Section.option_frm;
using Tunnel_Cross_Section.相关类;
using System.IO;
using System.Threading;
using TunnelClasses;
using Microsoft.Win32;
using Microsoft.Office.Interop.Excel;
using Tunnel_Cross_Section.DeviceConfig;

namespace Tunnel_Cross_Section
{
    public partial class Mfrm : Office2007RibbonForm
    {
        public List<Projects> current_projects;//用来管理当前的工程量
        public Projects cur_prj;
        public DataBase m_db = null;
        System.Resources.ResourceManager resources;//用来调用资源文件
        public CAD_Class cad;
        public Mfrm()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
            panelEx1.Style.BackColor1.Color = Color.LightBlue;
            panelEx1.Style.BackColor2.Color = Color.White;
            panelEx1.Style.GradientAngle = 45;
            resources = new System.Resources.ResourceManager("Tunnel_Cross_Section.pic", System.Reflection.Assembly.GetExecutingAssembly());
            Connect_To_DataBase();
            current_projects = new List<Projects>();//初始化程序管理List
            
        }


        //连接Sql数据库的函数,无脑型,不用管.
        private void Connect_To_DataBase()
        {
            DataBaseConfig c = new DataBaseConfig();
            m_db = c.ConnectDatabase();
            //DataBase db = null;
            //string computer = System.Environment.MachineName;
            //本地连接
            //RegistryKey rk = Registry.LocalMachine.OpenSubKey(@"SOFTWARE/Microsoft/Microsoft SQL Server");
            //String[] instances = (String[])rk.GetValue("InstalledInstances");
            //if (instances.Length > 0)
            //{
            //    foreach (String element in instances)
            //    {
            //        if (element != "MSSQLSERVER")
            //            computer = computer + "\\" + element;
            //           // Console.WriteLine(System.Environment.MachineName + @"/" + element);
            //    }
            //}

            //if (DataBase.ConnectToDataBase("sqlserver", "",
            //         computer, "", "", "cross_section", true, ref db))
            //{
            //    m_db = db;
                
            //}
            //if (!DataBase.ConnectToDataBase("sqlserver", "192.168.5.47", "1433", "",
            // computer + "\\SQLEXPRESS", "sa", "123", "cross_section", false, ref db))
            //{
            //    m_db = null;
            //}
            //else
            //{
            //    m_db = db;
            //}
            // if (!DataBase.ConnectToDataBase("sqlserver", "192.168.5.32", "1433", "",
            //     computer + "\\SQLEXPRESS", "sa", "123", "cross_section", false, ref db))
            // {

               //if (MessageBox.Show("无法连接数据库\"cross_section\" ,是否要在本地创建新的数据库?", "Information", MessageBoxButtons.YesNo) == DialogResult.Yes)
            //{
            //    //string myExecuteQuery;
            //    //myExecuteQuery = "CREATE DATABASE cross_section ON PRIMARY " +
            //    //"(NAME = cross_section, " +
            //    //"FILENAME = 'C:\\cross_section.mdf', " +
            //    //"SIZE = 5MB, MAXSIZE = 10MB, FILEGROWTH = 10%) " +
            //    //"LOG ON (NAME = cross_section_log, " +
            //    //"FILENAME = 'C:\\cross_section.ldf', " +
            //    //"SIZE = 5MB, " +
            //    //"MAXSIZE = 200MB, " +
            //    //"FILEGROWTH = 10%)";

               //    //SqlConnection mySqlConnection = new SqlConnection("server=" + computer + "\\SQLEXPRESS;integrated security = true");
            //    //SqlCommand myCommand = new SqlCommand(myExecuteQuery, mySqlConnection);
            //    //myCommand.Connection.Open();
            //    //myCommand.ExecuteNonQuery();
            //    //mySqlConnection.Close();
            //    //bool c = DataBase.ConnectToDataBase("sqlserver", "",
            //    //    computer + "\\SQLEXPRESS", "", "", "cross_section", true, ref db);
            //    //m_db = db;

               //}
            //else
            //{

               //    return;
            //}
            //   }
       
        }


        #region 新建工程
        private void btn_new_prj_Click(object sender, EventArgs e)
        {
            menue_frm.new_prj_from frm = new Tunnel_Cross_Section.menue_frm.new_prj_from(m_db,this);
            frm.ShowDialog();
            Label.Text = "开始新建区间";


        }
        #endregion

        #region 帮助信息
        private void btn_help_Click(object sender, EventArgs e)
        {
            option_frm.message_frm frm = new Tunnel_Cross_Section.option_frm.message_frm("你不会真指望我做个帮助文\r\n档吧!\r\n自己慢慢试!"
                ,"提示",0);
            frm.buttonX1.Visible = false;
            frm.ShowDialog();
            frm.Close();

        }
        #endregion 



        #region 
        //用来追踪现有的工程,并形成工程列表
        public void update_projects()
        {
            if (current_projects.Count == 0)
            {
                return;
            }
            tree_prj.Nodes[0].Nodes.Clear();
            for (int i = 0; i < current_projects.Count; i++)
            {
                DevComponents.AdvTree.Node new_node = new Node();
                new_node.Text = current_projects[i].section_name;
                new_node.Cells.Add(new Cell());
                new_node.Cells[1].Images.Image = ((System.Drawing.Image)(resources.GetObject("cancel")));
                tree_prj.Nodes[0].Nodes.Add(new_node);
                tree_prj.Nodes[0].Text = "当前工程(" + (tree_prj.Nodes.Count).ToString() + "个工程)";
            }
            tree_prj.Refresh();
        }
        

        #endregion

        #region 打开区间列表
        private void btn_open_Click(object sender, EventArgs e)
        {
            menue_frm.open_project_frm frm = new Tunnel_Cross_Section.menue_frm.open_project_frm(this, m_db);
            frm.MdiParent = this;
            frm.WindowState = FormWindowState.Maximized;
            frm.Show();
            frm.Update();
            Label.Text = "打开区间";
        }
        #endregion

        #region 删除某个工程
        private void tree_prj_NodeClick(object sender, TreeNodeMouseEventArgs e)
        {
            if (tree_prj.Nodes[0].Nodes.Count == 0)
            {
                return;
            }
            if (e.Button == MouseButtons.Left && e.Node.SelectedCell.Images.Image != null && e.Node.SelectedCell.Text == "")
            {
                int i = e.Node.Index;
                tree_prj.Nodes[0].Nodes.RemoveAt(i);

                tree_prj.Nodes[0].Text = "当前工程(" + tree_prj.Nodes[0].Nodes.Count.ToString() + "个工程)";
                Label.Text = "已关闭区间: " + current_projects[i].section_name;

                string frm_name = current_projects[i].section_name;
                for (int k = 0; k < this.MdiChildren.Length; k++)
                {
                    if (MdiChildren[k].Text.Contains(frm_name) == true)
                    {
                        MdiChildren[k].Close();
                    }
                }
                current_projects.RemoveAt(i);
                tree_prj.Refresh();

            }
        }
        #endregion


        #region 用户鼠标点击,切换活动工程
        private void tree_prj_AfterNodeSelect(object sender, AdvTreeNodeEventArgs e)
        {
            if (tree_prj.Nodes[0].Nodes.Count == 0)
            {
                return;
            }
            if (e.Node.Level == 1)
            {
                int i = e.Node.Index;
                cur_prj = current_projects[i];
                Label.Text = "已选择区间: " + cur_prj.section_name;
            }
        }
        #endregion

        private void btn_go_section_Click(object sender, EventArgs e)
        {

            if (current_projects.Count == 1)
            {
                cur_prj = current_projects[0];
            }
            else if (cur_prj == null)
            {
                option_frm.message_frm frm = new Tunnel_Cross_Section.option_frm.message_frm("请选择要进行操作的区间!"
                               , " 错误", 3);
                frm.ShowDialog();
                frm.Close();
                return;

            }
            do_section_frm frm1 = new do_section_frm(m_db, this);
            frm1.MdiParent = this;
            frm1.WindowState = FormWindowState.Maximized;
            if (frm1.no == 0)
            {
                frm1.Close();
                Label.Text = "收敛处理已取消";
                return;
            }
            try
            {
                frm1.Show();
            }
            catch
            {
                frm1.Dispose();
                frm1 = null;
                frm1 = new do_section_frm(m_db, this);
                frm1.MdiParent = this;
                frm1.WindowState = FormWindowState.Maximized;
                frm1.Show();
            }
        }

        #region 生成报告
        //点此,来生成报告
        private void buttonItem2_Click(object sender, EventArgs e)
        {
            Thread th = new Thread(new ThreadStart(generate_report));
            th.Start();
            

        }
        void generate_report()
        {
            this.UseWaitCursor = true;
            if (cur_prj == null)
            {
                message_frm aa = new message_frm("当前项目为空!", "错误", 0);
                aa.ShowDialog();
                aa.Close();
                return;
            }
            int index = tabStrip.SelectedTabIndex;
            if (index < 0)
            {
                message_frm aa = new message_frm("要在激活收敛处理\r\n的情况下才能生成报告!", "错误", 0);
                aa.ShowDialog();
                aa.Close();
                this.UseWaitCursor = false;
                return;
            }
            Form frm = this.MdiChildren[index];
            string type = frm.GetType().Name;
            if (type != "do_section_frm")
            {
                message_frm aa = new message_frm("要在激活收敛处理\r\n的情况下才能生成报告!", "错误", 0);
                aa.ShowDialog();
                aa.Close();
                this.UseWaitCursor = false;
                return;
            }
            object miss = Type.Missing;
            do_section_frm do_frm = frm as do_section_frm;
            string path = System.Windows.Forms.Application.StartupPath + "\\报表\\"
                + do_frm.Text + ".xls";
            bool IsSepecial = this.cur_prj.IsSepecial();
            //把这个excel命名成区间+期数的格式.
            try
            {
                if (File.Exists(path) == true)
                {
                    File.Delete(path);
                }
                if (IsSepecial == false)
                {
                    File.Copy(System.Windows.Forms.Application.StartupPath + "\\template.xls", path);
                }
                else
                {
                    string templatepath = System.Windows.Forms.Application.StartupPath + "\\" + this.cur_prj.section_name + "模板.xls";
                    if (File.Exists(templatepath) == false)
                    {
                        templatepath = System.Windows.Forms.Application.StartupPath + "\\templatespecial.xls";
                    }

                    File.Copy(templatepath, path);
                }
            }
            catch (Exception a)
            {
                message_frm aa = new message_frm(a.Message, "出错", 0);
                aa.ShowDialog();
                aa.Close();
                this.UseWaitCursor = false;
                return;
            }
            ReportHelper h = new ReportHelper();
            h.IsSpecial = IsSepecial;
            h.mfrm = this;
            h.do_frm = do_frm;
            h.CreateReport(path);
        }
        #endregion

        #region 窗体结束,注销cad变量
        private void Mfrm_FormClosed(object sender, FormClosedEventArgs e)
        {
      
        }
        #endregion

        private void buttonItem1_Click(object sender, EventArgs e)
        {
            DeviceConfigFrm frm = new DeviceConfigFrm(m_db);
            frm.MdiParent = this;
            frm.WindowState = FormWindowState.Maximized;
            frm.Show();
            frm.Update();
            Label.Text = "校准仪器测距常数差";
        }

        private void buttonItem3_Click(object sender, EventArgs e)
        {
            foreach (Form f in this.MdiChildren)
            {
                f.Close();
            }
            DataBaseConfig c = new DataBaseConfig();
            c.SetDataBaseType();
            m_db = c.ConnectDatabase();
        }
    }
}